//=======================================================
// 作者：KingSley
// 描述：
//=======================================================
using UnityEngine;
using System;
using System.Collections;
using System.Data;
using MySql.Data.MySqlClient;
using UnityEngine.UI;

namespace MVC
{
    public class PlayerMsgDB : MonoBehaviour
    {
        // 玩家信息数据模型对象
        public static PlayerMsgDB Db;

        // MySql连接器
        private MySqlConnection sqlConn;
        // MySql数据信息存储
        private String sqlStr;
        // MySql连接函数触发按钮
        private Button sqlConnectButton;
        // MsSql连接情况判断变量
        public bool IsCon = false;

        void Awake()
        {
            Db = this;
        }

        private void Start()
        {
            sqlConnectButton = GameObject.Find("ConnectButton").GetComponent<Button>();
            sqlConnectButton.onClick.RemoveAllListeners();
            sqlConnectButton.onClick.AddListener(ConnectClick);
        }

        /// <summary>
        /// 获取玩家信息模型数据
        /// </summary>
        /// <returns>PlayerMsgDB Db</returns>
        public static PlayerMsgDB GetDB()
        {
            return Db;
        }

        /// <summary>
        /// 连接数据库按钮响应事件
        /// </summary>
        public void ConnectClick()
        {
            if (IsCon == false)
            {
                Debug.Log("Connect");
                HandleMsg();
                Synchronization();
                IsCon = true;
                sqlConnectButton.gameObject.SetActive(false);
            }
        }

        /// <summary>
        /// 建立数据库连接
        /// </summary>
        public MySqlConnection GetSqlConn()
        {
            // 数据库连接SQL语句
            string connStr = "Database=unity;Data Source=127.0.0.1;User Id=root;Password=root;port=3306";
            sqlConn = new MySqlConnection(connStr);
            return sqlConn;
        }

        /// <summary>
        /// 获取数据库数据
        /// </summary>
        public void HandleMsg()
        {
            // 数据库
            sqlConn = GetSqlConn();
            try
            {
                sqlConn.Open();
                // 获取数据
                string cmdStr = "select * from PlayerMVC";
                MySqlCommand cmd = new MySqlCommand(cmdStr, sqlConn);
                try
                {
                    MySqlDataReader dataReader = cmd.ExecuteReader();
                    sqlStr = "";
                    while (dataReader.Read())
                    {
                        sqlStr += dataReader["playerLevel"] + ","
                            + dataReader["playerExperience"] + ","
                            + dataReader["playerFullExperience"] + ","
                            + dataReader["goldNum"] + ",";
                    }

                    dataReader.Close();
                }
                catch (Exception ex)
                {
                    Debug.LogError("[数据库]查询失败" + ex.Message);
                }
                sqlConn.Close();
            }
            catch (Exception ex)
            {
                Debug.LogError(ex.Message);
                return;
            }
        }

        /// <summary>
        /// 将数据库数据同步到模型
        /// </summary>
        public void Synchronization()
        {
            string[] strs = new string[5];
            strs = sqlStr.Split(new char[] { ',' });
            //同步到模型
            PlayerMsgModel.GetMod().PlayerLevel = int.Parse(strs[0]);
            PlayerMsgModel.GetMod().PlayerExperience = int.Parse(strs[1]);
            PlayerMsgModel.GetMod().PlayerFullExperience = int.Parse(strs[2]);
            PlayerMsgModel.GetMod().GoldNum = int.Parse(strs[3]);
        }

        /// <summary>
        /// 更新数据库信息为新数据信息
        /// </summary>
        public void UpdateDB()
        { 
            if (IsCon == true) 
            {
                Debug.Log("Update");
                // 数据库
                sqlConn = GetSqlConn();
                try
                {
                    sqlConn.Open();
                    // 存储数据
                    string cmdStr = "Update PlayerMVC set PlayerLevel=" + PlayerMsgModel.GetMod().PlayerLevel
                        + ", PlayerExperience=" + PlayerMsgModel.GetMod().PlayerExperience
                        + ", PlayerFullExperience=" + PlayerMsgModel.GetMod().PlayerFullExperience
                        + ", GoldNum=" + PlayerMsgModel.GetMod().GoldNum
                        + " where id =1;";
                    MySqlCommand cmd = new MySqlCommand(cmdStr, sqlConn);
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        Debug.LogError("[数据库]更新失败" + ex.Message);
                    }
                    sqlConn.Close();
                }
                catch (Exception ex)
                {
                    Debug.LogError(ex.Message);
                    return;
                }
            }
        }
    }
}
